<template>
  <div class="login">
    <div class="login_formb">
      <div class="title_container">
        <h3 class="title">内部文件传输及交流平台</h3>
      </div>
      <el-form :model="ruleForm" status-icon label-position="left" :rules="rules" ref="ruleForm" label-width="100px"
        class="login_form">
        <!-- 账号输入框 -->
        <el-form-item label="账 号" prop="userPin">
          <el-input v-model="ruleForm.userPin" autocomplete="off" placeholder="请输入账号"></el-input>
        </el-form-item>
        <!-- 密码输入框 -->
        <el-form-item label="密 码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass" show-password placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="validateCodeImg">
          <!-- <el-input type="password" v-model="ruleForm.validateCodeImg" autocomplete="off" placeholder="请输入验证码"></el-input> -->
          <el-col :span="12">
            <el-input v-model="ruleForm.validateCodeVal" autocomplete="off" placeholder="请输入验证码"
              @keyup.enter.native="handleLogin"></el-input>
          </el-col>
          <el-col :span="12">
            <el-image :src="validateCodeImg" @click="updateValImg"
              style="width: 150px; height: 50px;margin: 0 15px;"></el-image>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin">登录</el-button>
          <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { getValidateCode } from '@/api/login'
export default {
  name: 'LoginView',
  data () {
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('账号不能为空'));
      }
    };
    var validatePass = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入密码'));
      }
    };
    return {
      loginEncryptKey: "",//
      validateCodeImg: "",  // 用来存储验证码的base64数据
      validateCodeKey: "",  // 用来存储验证码的唯一标识
      ruleForm: {
        id: '01',
        userPin: '',
        pass: '',
        validateCodeVal: ""
      },
      rules: {
        userPin: [
          { validator: checkAge, trigger: 'blur' }
        ],
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
      }
    };
  },

  created () {
    this.getValidateCode();

  },
  mounted () {
    // 获取上次登录的账号
    const lastLogin = sessionStorage.getItem('userPin');
    if (lastLogin) {
      this.ruleForm.userPin = lastLogin;
    }
  },
  methods: {
    // 点击图片更新验证码
    updateValImg () {
      this.getValidateCode();
    },
    // 验证码
    async getValidateCode () {
      try {
        // 清除验证码输入的内容
        this.ruleForm.validateCodeVal = ''
        const { data } = await getValidateCode()
        console.log(data, "验证码获取");
        this.validateCodeImg = data.validateCodeImg
        this.validateCodeKey = data.validateCodeKey
        this.loginEncryptKey = data.loginEncryptKey
      } catch (error) {
        console.log(error);
      }
    },
    // 登录
    async handleLogin () {
      // 定义错误消息的映射关系
      if (this.ruleForm.userPin === "" || this.ruleForm.pass === "") {
        this.$message.error('账号或者密码为空！')
        return 
       }
      const errorMessages = {
        '验证码为空！': '验证码为空！',
        '账号或密码错误': '账号或密码错误',
        '验证码无效！': '验证码无效！'
      };
      try {
        const data = await this.$http.post('/auth/login', {
          userPin: this.ruleForm.userPin,
          userPwd: this.ruleForm.pass,  // 假设你有一个加密函数
          validateCodeKey: this.validateCodeKey,
          validateCodeVal: this.ruleForm.validateCodeVal,
          loginEncryptKey: this.loginEncryptKey
        })
        console.log(data);

        if (data.code === 0) {
          // 登录成功
          this.$message({
            type: 'success',
            message: '登录成功'
          });
          this.$router.push({ path: '/home/chat' });
          const token = data.data.token
          const expireTime = Date.now() + data.data.expire
          // 存储token和过期时间到sessionStorage
          sessionStorage.setItem("token", token);
          sessionStorage.setItem("expireTime", expireTime);
          // console.log("token和过期时间", token, expireTime);
          // localStorage.setItem('userPin', this.ruleForm.userPin); // 存储 userPin 到 localStorage
          sessionStorage.setItem('userPin', this.ruleForm.userPin);
        } else {
          const errorMessage = errorMessages[data.msg];
          this.getValidateCode();
          if (errorMessage) {
            // 显示错误信息
            this.$message({
              type: 'error',
              message: errorMessage
            });
          }
        }

      } catch (error) {
        console.error('登录失败', error);
        this.$message({
          type: 'error ',
          message: '登录成功'
        });
      }
    },
  }
};


</script>

<style scoped lang="scss">
@import "@/assets/style/variables.scss";


.login {
  width: 100%;
  min-height: 100%;
  height: 100%;
  overflow: hidden;
  background-position: center; // 将图片位置设置为充满整个屏幕
  position: relative;
  background: linear-gradient(to bottom, #102b5f, #3794d0);

  .login_formb {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    // 标题
    .title_container {
      position: relative;
      margin-bottom: 50px;

      .title {
        font-size: 60px;
        color: $light_gray;
        margin: 0px auto 20px auto;
        text-align: center;
        font-weight: bold;
      }
    }

    // 表单
    .login_form {
      position: relative;
      width: 500px;
      max-width: 100%;
      padding: 0px 35px 0;
      margin: 0 auto 50px;
      overflow: hidden;

      ::v-deep .el-form-item .el-form-item__label {
        color: #fff;
        font-size: 25px;
      }

      ::v-deep .el-button {
        padding: 15px 190px !important;
      }

      .el-button {
        font-size: 25px;
      }

      ::v-deep .el-form-item:nth-child(4) .el-form-item__content {
        margin-left: 0 !important;
        margin-top: 20px;
      }

      ::v-deep .el-form-item__error {
        font-size: 14px;
      }

      .el-form-item {
        margin-bottom: 30px;
      }
    }
  }

}
</style>